from flask import Blueprint, make_response, request, session, jsonify
from utils.captcha.captcha import captcha
from utils.ytx_sdk import ytx_send
import random
from models import db, UserInfo

user_blueprint = Blueprint('user', __name__, url_prefix='/user')


@user_blueprint.route('/image_code')
def image_code():
    # 　生成图像验证吗
    name, text, image = captcha.generate_captcha()
    print(text)
    # 保存数据后续对比
    session['image_code'] = text
    # 响应
    response = make_response(image)
    response.mimetype = 'image/png'

    return response


@user_blueprint.route('/sms_code')
def sms_code():
    mobile = request.args.get('mobile')
    image_code_request = request.args.get('image_code')
    if not all([mobile, image_code_request]):
        return jsonify(result=1)
    img_code_session = session.pop('image_code')
    if image_code_request != img_code_session:
        return jsonify(result=2)
    sms_code_value = str(random.randint(100000, 999999))
    session['sms_code'] = sms_code_value
    # ytx_send.sendTemplateSMS(mobile,['5',sms_code_value],1)
    print(sms_code_value)
    return jsonify(result=3)


@user_blueprint.route('/register', methods=['POST'])
def register():
    mobile = request.form.get('mobile')
    sms_code_request = request.form.get('sms_code')
    pwd = request.form.get('pwd')
    agree = request.form.get('agree')
    if not agree:
        return jsonify(result=3)
    if not all([mobile, sms_code_request, pwd]):
        return jsonify(result=1)
    sms_code_session = session.pop('sms_code')
    if sms_code_session != sms_code_request:
        return jsonify(result=2)
    if len(pwd) < 6:
        return jsonify(result=4)
    mobile_exists = UserInfo.query.filter_by(mobile=mobile).count()
    if mobile_exists:
        return jsonify(result=5)
    user = UserInfo()
    user.nick_name = mobile
    user.mobile = mobile
    user.password = pwd
    db.session.add(user)
    db.sessioncommit()
    return jsonify(result=6)


@user_blueprint.route('/login', methods=['POST'])
def login():
    mobile = request.form.get('mobile')
    pwd = request.form.get('pwd')
    if not all([mobile, pwd]):
        return jsonify(result=1)
    user = UserInfo.query.filter_by(mobile=mobile).first()
    if user:
        if user.check_pwd(pwd):
            session['user_id'] = user.id
            return jsonify(result=3,
                           avatar=user.avatar, nick_name=user.nick_name)
        else:
            return jsonify(result=4)
    else:
        return jsonify(result=2)


@user_blueprint.route('/logout')
def logout():
    session.pop('user_id')
    return jsonify(result=1)
    print('hello world')
